package com.ruoyi.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.app.domain.bo.AppToUserIdBo;
import com.ruoyi.app.domain.bo.AppUserFreeBo;
import com.ruoyi.app.domain.vo.AppAssetVo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.service.IAppAssetService;
import com.ruoyi.app.service.IAppDetailService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.BillType;
import com.ruoyi.common.enums.CoinType;
import com.ruoyi.common.enums.DetailEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OrderNumUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.app.domain.bo.AppAssetTransferBo;
import com.ruoyi.app.domain.vo.AppAssetTransferVo;
import com.ruoyi.app.domain.AppAssetTransfer;
import com.ruoyi.app.mapper.AppAssetTransferMapper;
import com.ruoyi.app.service.IAppAssetTransferService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 转增订单Service业务层处理
 *
 * @author app
 * @date 2025-06-24
 */
@RequiredArgsConstructor
@Service
public class AppAssetTransferServiceImpl implements IAppAssetTransferService {

    private final AppAssetTransferMapper baseMapper;
    private final IAppAssetService appAssetService;
    private final IAppDetailService appDetailService;


    /**
     * 查询转增订单
     */
    @Override
    public AppAssetTransferVo queryById(Long transferId) {
        return baseMapper.selectVoById(transferId);
    }

    /**
     * 查询转增订单列表
     */
    @Override
    public TableDataInfo<AppAssetTransferVo> queryPageList(AppAssetTransferBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppAssetTransfer> lqw = buildQueryWrapper(bo);
        Page<AppAssetTransferVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询转增订单列表
     */
    @Override
    public List<AppAssetTransferVo> queryList(AppAssetTransferBo bo) {
        LambdaQueryWrapper<AppAssetTransfer> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppAssetTransfer> buildQueryWrapper(AppAssetTransferBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppAssetTransfer> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), AppAssetTransfer::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getUserId() != null, AppAssetTransfer::getUserId, bo.getUserId());
        lqw.eq(bo.getToUserId() != null, AppAssetTransfer::getToUserId, bo.getToUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), AppAssetTransfer::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), AppAssetTransfer::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppAssetTransfer::getStatus, bo.getStatus());
        lqw.in(bo.getStatusList() != null && !bo.getStatusList().isEmpty(), AppAssetTransfer::getStatus, bo.getStatusList());
        return lqw;
    }

    /**
     * 新增转增订单
     */
    @Override
    public Boolean insertByBo(AppAssetTransferBo bo) {
        AppAssetTransfer add = BeanUtil.toBean(bo, AppAssetTransfer.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTransferId(add.getTransferId());
        }
        return flag;
    }

    /**
     * 修改转增订单
     */
    @Override
    public Boolean updateByBo(AppAssetTransferBo bo) {
        AppAssetTransfer update = BeanUtil.toBean(bo, AppAssetTransfer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改转增订单
     */
    @Override
    public Boolean updateByVo(AppAssetTransferVo vo) {
        AppAssetTransfer update = BeanUtil.toBean(vo, AppAssetTransfer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }


    /**
     * 修改转增订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(AppAssetTransferBo bo) {
        return updateByBo(bo);
    }

    /**
     * 确认转赠订单
     *
     * @param vo 订单信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmTransfer(AppAssetTransferVo vo) {
        boolean success = false;
        if (StringUtils.equals(vo.getType(), Constants.FAIL)) {
            success = appAssetService.addBalance(vo.getToUserId(), vo.getTransferEndNumber());
        } else {
            success = appAssetService.addIntegral(vo.getToUserId(), vo.getTransferEndNumber());
        }
        if (success) {
            if (StringUtils.equals(vo.getType(), Constants.FAIL)) {
                appDetailService.insert(vo.getToUserId(), vo.getTransferEndNumber(), BigDecimal.ZERO, BillType.IN.getCode(), CoinType.GOLD.getCode(), DetailEnums.TRANSFER11_GIVE.getCode(), DetailEnums.TRANSFER11_GIVE.getInfo(), vo.getUserId());
            } else {
                appDetailService.insert(vo.getToUserId(), vo.getTransferEndNumber(), BigDecimal.ZERO, BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.TRANSFER_INTEGRAL_GIVE.getCode(), DetailEnums.TRANSFER_INTEGRAL_GIVE.getInfo(), vo.getUserId());
            }

            //给别人增加积分的1.0倍贡献度
            appAssetService.addContribution(vo.getToUserId(), vo.getTransferEndNumber().multiply(new BigDecimal("1.0")).setScale(2, RoundingMode.HALF_UP));
            //日志
            appDetailService.insert(vo.getToUserId(),
                    vo.getTransferEndNumber().multiply(new BigDecimal("1.0")).setScale(2, RoundingMode.HALF_UP),
                    BigDecimal.ZERO, BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(),
                    DetailEnums.TRANSFER11_GIVE.getCode(), "用户"+vo.getUserId()+"转赠增加贡献度",
                    vo.getUserId());


            AppAssetTransferBo transferBo = new AppAssetTransferBo();
            transferBo.setStatus(Constants.TWO);
            transferBo.setEndTime(DateUtils.getNowDate());
            transferBo.setTransferId(vo.getTransferId());
            return update(transferBo);
        }
        return success;
    }

    /**
     * 确认转赠订单
     *
     * @param vo 订单信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean confirmTransfer2(AppAssetTransferVo vo) {
        boolean success = false;
        if (StringUtils.equals(vo.getType(), Constants.FAIL)) {
            success = appAssetService.addBalance(vo.getToUserId(), vo.getTransferEndNumber());
        } else {
            success = appAssetService.addIntegral(vo.getToUserId(), vo.getTransferEndNumber());
        }
        if (success) {
            if (StringUtils.equals(vo.getType(), Constants.FAIL)) {
                appDetailService.insert(vo.getToUserId(), vo.getTransferEndNumber(), BigDecimal.ZERO, BillType.IN.getCode(), CoinType.GOLD.getCode(), DetailEnums.TRANSFER11_GIVE.getCode(), DetailEnums.TRANSFER11_GIVE.getInfo(), vo.getUserId());
            } else {
                appDetailService.insert(vo.getToUserId(), vo.getTransferEndNumber(), BigDecimal.ZERO, BillType.IN.getCode(), CoinType.INTE.getCode(), DetailEnums.TRANSFER_INTEGRAL_GIVE.getCode(), DetailEnums.TRANSFER_INTEGRAL_GIVE.getInfo(), vo.getUserId());
            }
            AppAssetTransferBo transferBo = new AppAssetTransferBo();
            transferBo.setStatus(Constants.TWO);
            transferBo.setEndTime(DateUtils.getNowDate());
            transferBo.setTransferId(vo.getTransferId());
            return update(transferBo);
        }
        return success;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppAssetTransfer entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除转增订单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppAssetTransferBo createTransfer(Long id, AppUserVo userVo, BigDecimal balance, BigDecimal rate) {
        Boolean result = appAssetService.subtractBalance(id, balance);
        if (result) {
            AppAssetTransferBo transferBo = new AppAssetTransferBo();
            transferBo.setOrderNo(OrderNumUtils.getInstance().generateOrderNo());
            transferBo.setUserId(id);
            transferBo.setToUserId(userVo.getId());
            transferBo.setPhone(userVo.getPhone());
            transferBo.setTransferNumber(balance);
            BigDecimal freeNumber = balance.multiply(rate).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            transferBo.setTransferRate(freeNumber);
            transferBo.setTransferEndNumber(balance.subtract(freeNumber));
            transferBo.setType(Constants.FAIL);
            transferBo.setStatus(Constants.SUCCESS);
            if (insertByBo(transferBo)) {
                appDetailService.insert(id, balance, freeNumber, BillType.TO.getCode(), CoinType.GOLD.getCode(), DetailEnums.TRANSFER_SEND.getCode(), "转赠余额", userVo.getId());
                return transferBo;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelTransfer(AppAssetTransferVo transferVo) {
        AppAssetTransferBo transferBo = new AppAssetTransferBo();
        transferBo.setStatus(Constants.THREE);
        transferBo.setTransferId(transferVo.getTransferId());
        if (updateByBo(transferBo)) {
            String code;
            Boolean result;
            if (StringUtils.equals(transferVo.getType(), Constants.FAIL)) {
                code = CoinType.GOLD.getCode();
                result = appAssetService.addBalance(transferVo.getUserId(), transferVo.getTransferNumber());
            } else {
                code = CoinType.INTE.getCode();
                result = appAssetService.addIntegral(transferVo.getUserId(), transferVo.getTransferNumber());
            }
            if (result) {
                appDetailService.insert(transferVo.getUserId(), transferVo.getTransferNumber(), BigDecimal.ZERO, BillType.IN.getCode(), code, DetailEnums.CANCEL_SEND.getCode(), DetailEnums.CANCEL_SEND.getInfo(), null);
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean customerOrder(AppAssetTransferVo transferVo, AppAssetTransferBo bo) {
        if (StringUtils.equals(bo.getAppealStatus(), "2")) {
            String code;
            Boolean success = false;
            //退回卖家
            if (StringUtils.equals(transferVo.getType(), Constants.FAIL)) {
                code = CoinType.GOLD.getCode();
                success = appAssetService.addBalance(transferVo.getUserId(), transferVo.getTransferNumber());
            } else {
                code = CoinType.INTE.getCode();
                //连带手续费一并退回
                success = appAssetService.addIntegral(transferVo.getUserId(), transferVo.getTransferNumber().add(transferVo.getTransferRate()));

                //退回卖家贡献度
                appAssetService.addContribution(transferVo.getUserId(),
                        transferVo.getTransferNumber());
                //日志
                appDetailService.insert(transferVo.getUserId(),
                        transferVo.getTransferNumber(),
                        BigDecimal.ZERO, BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(),
                        DetailEnums.TRANSFER11_GIVE.getCode(), "申诉成功退回贡献度",
                        transferVo.getToUserId());
            }
            if (success) {
                transferVo.setAppealStatus("2");
                updateByVo(transferVo);
                appDetailService.insert(transferVo.getUserId(), transferVo.getTransferNumber().add(transferVo.getTransferRate()), BigDecimal.ZERO, BillType.IN.getCode(), code, DetailEnums.TRANSFER_CUSTOMER.getCode(), "转赠申诉退回", transferVo.getToUserId());
            }
            return success;
        }
        if (StringUtils.equals(bo.getAppealStatus(), "3")) {
            String code;
            Boolean success = false;
            //买家到账
            if (StringUtils.equals(transferVo.getType(), Constants.FAIL)) {
                code = CoinType.GOLD.getCode();
                success = appAssetService.addBalance(transferVo.getToUserId(), transferVo.getTransferEndNumber());
            } else {
                code = CoinType.INTE.getCode();
                success = appAssetService.addIntegral(transferVo.getToUserId(), transferVo.getTransferEndNumber());

                //买家贡献度
                appAssetService.addContribution(transferVo.getToUserId(),
                        transferVo.getTransferNumber());
                //日志
                appDetailService.insert(transferVo.getToUserId(),
                        transferVo.getTransferNumber().multiply(new BigDecimal("1.0").setScale(2, RoundingMode.HALF_UP)),
                        BigDecimal.ZERO, BillType.IN.getCode(), CoinType.CONTRIBUTION.getCode(),
                        DetailEnums.TRANSFER11_GIVE.getCode(), "申诉成功到账贡献度",
                        transferVo.getToUserId());

            }
            if (success) {
                transferVo.setAppealStatus("3");
                updateByVo(transferVo);
                appDetailService.insert(transferVo.getToUserId(), transferVo.getTransferEndNumber(), BigDecimal.ZERO, BillType.IN.getCode(), code, DetailEnums.TRANSFER_CUSTOMER.getCode(), "转赠申诉到账", transferVo.getUserId());
            }
            return success;
        }
        return false;
    }

    @Override
    public Boolean dongjie(AppToUserIdBo bo) {
        //冻结用户24积分小时
        if(bo.getType()==1){
            appAssetService.freeze(bo.getUserId());
        }else if (bo.getType()==0){
            appAssetService.unfreeze(bo.getUserId());
        }
        return true;
    }

    @Override
    public Boolean freeze(AppUserFreeBo appUserFreeBo) {
        LambdaQueryWrapper<AppAssetTransfer> appAssetTransferLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appAssetTransferLambdaQueryWrapper.eq(AppAssetTransfer::getTransferId, appUserFreeBo.getTransferId());
        AppAssetTransfer appAssetTransfer = baseMapper.selectOne(appAssetTransferLambdaQueryWrapper);
        if (appAssetTransfer!=null){
            appAssetTransfer.setAppealStatus("1");
        }
        baseMapper.update(appAssetTransfer,appAssetTransferLambdaQueryWrapper);
        return  appAssetService.freeze(appUserFreeBo.getUserId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppAssetTransferBo createTransferIntegral(Long id, AppUserVo userVo, BigDecimal balance, BigDecimal rate) {
        //多扣除手续费
        Boolean result = appAssetService.subtractIntegral(id, balance.add(balance.multiply(rate).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP)));
        //给转赠人 扣除 转赠数量的贡献度
        appAssetService.subContribution(id, balance);
        //日志
        appDetailService.insert(id,
                balance,
                BigDecimal.ZERO, BillType.TO.getCode(), CoinType.CONTRIBUTION.getCode(),
                DetailEnums.TRANSFER11_GIVE.getCode(), "转赠给"+userVo.getId()+"减少贡献度",
                userVo.getId());

        if (result) {
            AppAssetTransferBo transferBo = new AppAssetTransferBo();
            transferBo.setOrderNo(OrderNumUtils.getInstance().generateOrderNo());
            transferBo.setUserId(id);
            transferBo.setToUserId(userVo.getId());
            transferBo.setPhone(userVo.getPhone());
            transferBo.setTransferNumber(balance);
            BigDecimal freeNumber = balance.multiply(rate).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            transferBo.setTransferRate(freeNumber);
            transferBo.setTransferEndNumber(balance);
            transferBo.setType(Constants.TWO);
            transferBo.setStatus(Constants.SUCCESS);
            if (insertByBo(transferBo)) {
                appDetailService.insert(id, balance, freeNumber, BillType.TO.getCode(), CoinType.INTE.getCode(), DetailEnums.TRANSFER_INTEGRAL_SEND.getCode(), "转赠积分", userVo.getId());
                return transferBo;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void downOrder(AppAssetTransferVo e) {
        AppAssetTransferBo transferBo = new AppAssetTransferBo();
        transferBo.setStatus(Constants.TWO);
        transferBo.setTransferId(e.getTransferId());
        transferBo.setEndTime(DateUtils.getNowDate());
        update(transferBo);
    }
}
